package com.example.loginpage.InputUtil

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okio.IOException
import org.json.JSONObject

class OCRViewModel:ViewModel() {
    private val _accessToken = MutableLiveData<String>()
    val accessToken: LiveData<String> = _accessToken

    private val _myWords = MutableLiveData<String>()
    val myWords: LiveData<String> = _myWords

    fun clearMyWords(){
        _myWords.postValue("null")
    }
    fun getIAM(ak: String, sk: String) {
        var iamToken: String = ""

        viewModelScope.launch(Dispatchers.IO) {
            val client = OkHttpClient()
            val requestUrl = "https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens"
            val mediaType = "application/json; charset=utf-8".toMediaTypeOrNull()
            val body = "{\"auth\":{\"identity\":{\"methods\":[\"hw_ak_sk\"],\"hw_ak_sk\":{\"access\":{\"key\":\"$ak\"},\"secret\":{\"key\":\"$sk\"}}},\"scope\":{\"project\":{\"name\":\"cn-north-4\"}}}}"
                .toRequestBody(mediaType)

            val request = Request.Builder()
                .url(requestUrl)
                .post(body)
                .build()

            try {
                val response: Response = client.newCall(request).execute()
                if (response.isSuccessful) {
                    iamToken = response.header("X-Subject-Token").orEmpty()
                    withContext(Dispatchers.Main) {
                        // 更新UI或处理成功情况
                        _accessToken.postValue(iamToken)
                    }
                } else {
                    throw IOException("Unexpected code $response")
                }
            } catch (e: IOException) {
                withContext(Dispatchers.Main) {
                    // 处理错误情况
                    e.printStackTrace()
                }
            }
        }
    }

    private suspend fun performOCRRequest(image: String) : List<String>{
        val requestUrl = "https://ocr.cn-north-4.myhuaweicloud.com/v2/d8047c5a9ef04fe3bf7d842c0ab92951/ocr/general-text"
        val token = accessToken.value.toString()
        val mediaType = "application/json; charset=utf-8".toMediaTypeOrNull()
        val detectDirection = false
        val quickMode = false
        val body =
            "{\"image\":\"$image\",\"detect_direction\":$detectDirection,\"quick_mode\":$quickMode}".toRequestBody(
                mediaType
            )

        val request = Request.Builder()
            .url(requestUrl)
            .post(body)
            .addHeader("Content-Type", "application/json")
            .addHeader("X-Auth-Token", token)
            .build()
        return withContext(Dispatchers.IO){
            try {
                val client = OkHttpClient()
                val response: Response = client.newCall(request).execute()
                if (response.isSuccessful) {
                    val responseBody = response.body?.string() ?: ""
                    val allWords = extractWordsFromJSON(responseBody)
                    allWords
                } else {
                    throw IOException("Unexpected code $response")
                }
            } catch (e: IOException) {
                e.printStackTrace()
                throw e
            }
        }
    }

    fun getOCRRequest(base64Data: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val result = performOCRRequest(base64Data)
                withContext(Dispatchers.Main) {
                    var allWords = ""
                    for (word in result){
                        allWords+=word
                        allWords+=" "
                    }
                    _myWords.postValue(allWords)
                }
            } catch (e: IOException) {
                withContext(Dispatchers.Main) {
                    // 处理错误情况，例如显示错误消息
                    e.printStackTrace()
                }
            }
        }
    }
    private fun extractWordsFromJSON(jsonString: String): List<String> {
        // 使用JSON解析库解析JSON字符串
        val json = JSONObject(jsonString)
        val result = json.getJSONObject("result")
        val wordsBlockList = result.getJSONArray("words_block_list")

        // 初始化words列表
        val words = mutableListOf<String>()

        // 遍历words_block_list并提取所有words
        for (i in 0 until wordsBlockList.length()) {
            val wordsBlock = wordsBlockList.getJSONObject(i)
            val word = wordsBlock.getString("words")
            words.add(word)
        }
        // 返回words列表
        return words
    }
}